package com.strongbj.iot.devices.dam.sub.dacai.request.handle;

import java.io.UnsupportedEncodingException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.strongbj.core.util.ByteUtil;
import com.strongbj.iot.devices.dam.common.AbstractTaskDelayedRunnable;
import com.strongbj.iot.devices.dam.common.DAMManager;
import com.strongbj.iot.devices.dam.common.ITaskManager;
import com.strongbj.iot.devices.dam.message.DAMMessage;
import com.strongbj.iot.devices.dam.message.DAMMessageFactory;
import com.strongbj.iot.devices.dam.response.handle.v1.DAMV1Handle;
import com.strongbj.iot.devices.dam.response.handle.v1.TemperatureAndHumidityHandle;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;

/**
 * 更新大彩目标服务器网络参数的显示
 * @author yuzhantao
 *
 */
public class UpdateDaCaiServerNetPageParams extends DAMV1Handle {
	private static Logger logger = LogManager.getLogger(TemperatureAndHumidityHandle.class.getName());
	private static final byte SCREEN_ID = (byte) 4; // 网络屏幕ID
	private static final byte SERVER_IP_TEXT_ID = (byte) 4; // IP控件ID（文本框在屏幕中的ID）
	private static final byte SERVER_PORT_TEXT_ID = (byte) 5; // 子网掩码控件ID（文本框在屏幕中的ID）
	private static final String STRING_CODE = "GBK";
	private static final DAMMessageFactory damMessageFactory = new DAMMessageFactory(); // DAM消息工厂

	@Override
	protected boolean isHandleDAMMessage(DAMMessage t) {
		if (t.getCommand() == 0x15) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public Object handle(ChannelHandlerContext ctx, DAMMessage t) {
		byte[] srcDatas = t.getDatas();
		// 在网络设置屏幕中设置服务器IP显示框显示的值
		String ip = ByteUtil.bytesToUbyte(srcDatas, 0) + "." + ByteUtil.bytesToUbyte(srcDatas,1) + "."
				+ ByteUtil.bytesToUbyte(srcDatas,2) + "." + ByteUtil.bytesToUbyte(srcDatas,3);
		String port = String.valueOf(ByteUtil.byteArrToShort(new byte[]{srcDatas[5], srcDatas[4]}));
		
		ITaskManager taskManager = DAMManager.getTaskManager(ByteUtil.byteArrToHexString(t.getAddressCode()));
		taskManager.addSendTask(new AbstractTaskDelayedRunnable() {
			@Override
			protected void taskRun() {
				try {
					sendMessage(ctx, t.getAddressCode(), SCREEN_ID, SERVER_IP_TEXT_ID, ip,SERVER_PORT_TEXT_ID,port);
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
			}
		});
		
		return null;
	}

	private void sendMessage(ChannelHandlerContext ctx, byte[] devAddress, byte screenId, byte ipControlId, String ipContent,
			byte portControlId, String port)
			throws UnsupportedEncodingException {
		byte[] datas = createUpdateTextControlMessage(devAddress, screenId, ipControlId, ipContent,portControlId,port);
		ChannelFuture cf = ctx.channel().writeAndFlush(Unpooled.copiedBuffer(datas));
		cf.addListener(new ChannelFutureListener() {
			@Override
			public void operationComplete(ChannelFuture future) throws Exception {
				if (future.isSuccess()) {
					logger.info("向屏幕下发设置目标地址命令到文本控件成功 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				} else {
					logger.error("向屏幕下发设置目标地址命令到文本控件失败 下发命令={}  ", ByteUtil.byteArrToHexString(datas, true));
				}
			}
		});
	}

	private byte[] createUpdateTextControlMessage(byte[] devAddress, byte screenId, byte ipControlId, String ipContent,
			byte portControlId, String port)
			throws UnsupportedEncodingException {
		byte[] bIpContent = ipContent.getBytes(STRING_CODE);
		byte[] bPortContent = port.getBytes(STRING_CODE);
		byte[] destDatas = new byte[bIpContent.length+bPortContent.length + 21];
		destDatas[0] = (byte) 0xEE;
		destDatas[1] = (byte) 0xB1;
		destDatas[2] = (byte) 0x12;
		destDatas[3] = (byte) 0x00;
		destDatas[4] = screenId;
		
		// 设置服务器IP
		destDatas[5] = (byte) 0x00;
		destDatas[6] = ipControlId;
		System.arraycopy(ByteUtil.shortToByteArr(Integer.valueOf(bIpContent.length).shortValue()), 0, destDatas, 7, 2);
		System.arraycopy(bIpContent, 0, destDatas, 9, bIpContent.length);
		int offset = 9 + bIpContent.length;
		// 设置端口
		destDatas[offset] = (byte) 0x00;
		destDatas[offset+1] = portControlId;
		offset+=2;
		destDatas[offset] = (byte) 0x00;
		destDatas[offset+1] = Integer.valueOf(bPortContent.length).byteValue();
		offset+=2;
		System.arraycopy(bPortContent, 0, destDatas, offset, bPortContent.length);
		offset += bPortContent.length;
		// 设置协议尾
		destDatas[offset] = (byte) 0xFF;
		destDatas[offset + 1] = (byte) 0xFC;
		destDatas[offset + 2] = (byte) 0xFF;
		destDatas[offset + 3] = (byte) 0xFF;
		return damMessageFactory.createDAMMessage(ByteUtil.longToBytes(System.currentTimeMillis()), devAddress, // 设备编号
				(byte) 0, // 设备类型，默认填0
				(byte) 0, // 版本号，默认填0
				(byte) 0xFF, // 设置设备编号命令
				destDatas // 设置设备编号
		);
	}
}

